package com.neuedu.his.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neuedu.his.po.Checkapply;
import com.neuedu.his.po.Department;
import com.neuedu.his.po.Expenseclass;
import com.neuedu.his.po.Fmeditem;
import com.neuedu.his.po.Constantitem;
import com.neuedu.his.po.Medicalrecord;
import com.neuedu.his.po.Register;
import com.neuedu.his.po.User;
import com.neuedu.his.service.CheckapplyService;
import com.neuedu.his.service.ConstantitemService;
import com.neuedu.his.service.DepartmentService;
import com.neuedu.his.service.ExpenseclassService;
import com.neuedu.his.service.FmeditemService;
import com.neuedu.his.service.MedicalrecordService;
import com.neuedu.his.service.RegisterService;
import com.neuedu.his.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/doctor")
public class DoctorWorkstationController {

    @Autowired private MedicalrecordService  recordService;
    @Autowired private RegisterService       registerService;
    @Autowired private UserService           userService;
    @Autowired private CheckapplyService     applyService;
    @Autowired private FmeditemService       itemService;
    @Autowired private DepartmentService     deptService;
    @Autowired private ExpenseclassService   ExpenseclassService;
    @Autowired private ConstantitemService   constantitemService;
    // ---------------- 病历首页 ----------------

    @GetMapping("/record/{registId}")
    public ResponseEntity<Medicalrecord> getRecord(@PathVariable Integer registId) {
        // 1. 拉病历
        Medicalrecord rec = recordService.getOne(
                new LambdaQueryWrapper<Medicalrecord>()
                        .eq(Medicalrecord::getRegistid, registId)
                        .last("LIMIT 1")
        );
        if (rec == null) {
            rec = new Medicalrecord();
            rec.setRegistid(registId);
        }

        // 2. 拉所有已完成结果录入的检验/检查申请
        List<Checkapply> done = applyService.list(
                new LambdaQueryWrapper<Checkapply>()
                        .eq(Checkapply::getRegistid,   registId)
                        .eq(Checkapply::getRecordtype, 2)
                        .eq(Checkapply::getState,      6)
        );

        // 3. 拼成多行 “项目：结果” 文本
        String joined = done.stream().map(ca -> {
            Fmeditem fi = itemService.getById(ca.getItemid());
            String name = fi != null ? fi.getItemname() : "未知项目";
            String result = Optional.ofNullable(ca.getResult()).orElse("");
            return name + "：" + result;
        }).collect(Collectors.joining("\n"));

        // 4. 塞回 rec.checkresult
        rec.setCheckresult(joined);

        return ResponseEntity.ok(rec);
    }

    @PostMapping("/record")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Medicalrecord> saveRecord(@RequestBody Medicalrecord vo) {
        if (vo.getId() == null) {
            Register reg = registerService.getById(vo.getRegistid());
            vo.setCasenumber(reg.getCasenumber());
            recordService.save(vo);
            if (Objects.equals(vo.getCasestate(), 2)) {
                registerService.update(
                        new LambdaUpdateWrapper<Register>()
                                .eq(Register::getId, vo.getRegistid())
                                .set(Register::getVisitstate, 3)
                );
            }
            return ResponseEntity.ok(vo);
        }
        var uw = new LambdaUpdateWrapper<Medicalrecord>()
                .eq(Medicalrecord::getId, vo.getId());
        if (vo.getReadme()       != null) uw.set(Medicalrecord::getReadme,       vo.getReadme());
        if (vo.getPresent()      != null) uw.set(Medicalrecord::getPresent,      vo.getPresent());
        if (vo.getPresenttreat() != null) uw.set(Medicalrecord::getPresenttreat, vo.getPresenttreat());
        if (vo.getHistory()      != null) uw.set(Medicalrecord::getHistory,      vo.getHistory());
        if (vo.getAllergy()      != null) uw.set(Medicalrecord::getAllergy,      vo.getAllergy());
        if (vo.getPhysique()     != null) uw.set(Medicalrecord::getPhysique,     vo.getPhysique());
        if (vo.getProposal()     != null) uw.set(Medicalrecord::getProposal,     vo.getProposal());
        if (vo.getCareful()      != null) uw.set(Medicalrecord::getCareful,      vo.getCareful());
        if (vo.getCheckresult()  != null) uw.set(Medicalrecord::getCheckresult,  vo.getCheckresult());
        if (vo.getDiagnosis()    != null) uw.set(Medicalrecord::getDiagnosis,    vo.getDiagnosis());
        if (vo.getHandling()     != null) uw.set(Medicalrecord::getHandling,     vo.getHandling());
        if (vo.getCasestate()    != null) uw.set(Medicalrecord::getCasestate,    vo.getCasestate());
        recordService.update(null, uw);

        if (Objects.equals(vo.getCasestate(), 2)) {
            registerService.update(
                    new LambdaUpdateWrapper<Register>()
                            .eq(Register::getId, vo.getRegistid())
                            .set(Register::getVisitstate, 3)
            );
        }
        return ResponseEntity.ok(recordService.getById(vo.getId()));
    }

    // ---------------- 患者列表 ----------------

    @GetMapping("/patients")
    public ResponseEntity<IPage<Register>> listPatients(
            @RequestHeader(value="X-User-Id", required=false) Integer headerUserId,
            @RequestParam(value="userid",     required=false) Integer paramUserId,
            @RequestParam(required=false)     Integer deptid,
            @RequestParam(defaultValue="my")  String mode,
            @RequestParam(defaultValue="")    String kw,
            @RequestParam(defaultValue="unseen") String type,
            @RequestParam(defaultValue="1")   long page,
            @RequestParam(defaultValue="20")  long pageSize
    ) {
        Integer userId = headerUserId != null ? headerUserId : paramUserId;
        var qw = new QueryWrapper<Register>().like("RealName", kw);
        if ("dept".equals(mode) && deptid != null) {
            qw.eq("DeptID", deptid);
        } else if (userId != null) {
            qw.eq("UserID", userId);
        }
        if ("unseen".equals(type)) {
            qw.between("VisitState", 2, 3).orderByAsc("RegistTime");
        } else {
            qw.ge("VisitState", 4).orderByDesc("RegistTime");
        }
        IPage<Register> result = registerService.page(new Page<>(page, pageSize), qw);
        return ResponseEntity.ok(result);
    }

    // ------------ 检验申请草稿管理 ------------

    @GetMapping("/checkapply/items")
    public ResponseEntity<List<Fmeditem>> listItems(@RequestParam(value="kw", required=false) String kw) {
        var qw = new QueryWrapper<Fmeditem>();
        if (kw != null && !kw.isEmpty()) qw.like("ExpClassID", kw).or().like("ItemName", kw);
        return ResponseEntity.ok(itemService.list(qw));
    }

    @GetMapping("/checkapply")
    public ResponseEntity<List<Map<String,Object>>> listCheckapply(
            @RequestParam("registId") Integer registId
    ) {
        var list = applyService.list(new LambdaQueryWrapper<Checkapply>()
                .eq(Checkapply::getRegistid,   registId)
                .eq(Checkapply::getRecordtype, 2)
        );

        var out = new ArrayList<Map<String,Object>>();
        for (var ca : list) {
            Fmeditem   fi = itemService.getById(ca.getItemid());
            Department dp = deptService.getById(fi.getDeptid());
            Expenseclass ec = ExpenseclassService.getById(fi.getExpclassid());

            Map<String,Object> m = new HashMap<>();
            m.put("id",         ca.getId());
            m.put("category",   ec.getExpname());
            m.put("name",       fi.getItemname());
            m.put("deptName",   dp.getDeptname());
            m.put("isUrgent",   ca.getIsurgent());
            m.put("state",      ca.getState());
            m.put("unitPrice",  fi.getPrice());
            m.put("num",        ca.getNum());
            m.put("objective",  ca.getObjective());
            m.put("result",     ca.getResult());
            out.add(m);
        }
        return ResponseEntity.ok(out);
    }

    @PostMapping("/checkapply")
    public ResponseEntity<?> addCheckapply(
            @RequestBody Checkapply vo,
            @RequestHeader(value = "X-User-Id", required = false) Integer userId
    ) {
        if (vo.getRegistid() == null || vo.getItemid() == null) {
            return ResponseEntity.badRequest().body("注册ID或项目ID不能为空");
        }

        Fmeditem item = itemService.getById(vo.getItemid());
        if (item == null) {
            return ResponseEntity.badRequest().body("找不到项目");
        }

        // ✅ 自动查找对应病历ID
        Medicalrecord record = recordService.getOne(
                new LambdaQueryWrapper<Medicalrecord>()
                        .eq(Medicalrecord::getRegistid, vo.getRegistid())
                        .last("LIMIT 1")
        );
        if (record == null) {
            return ResponseEntity.badRequest().body("未找到对应病历");
        }
        vo.setMedicalid(record.getId());  // ✅ 设置进去

        vo.setName(item.getItemname());
        vo.setCreationtime(new Date());
        vo.setState(1);
        vo.setRecordtype(2);
        if (userId != null) {
            vo.setDoctorid(userId);
        }

        applyService.save(vo);
        return ResponseEntity.ok(vo);
    }

    @PutMapping("/checkapply/draft")
    public ResponseEntity<?> updateDraft(@RequestBody List<Checkapply> ups) {
        ups.forEach(applyService::updateById);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/checkapply/open")
    public ResponseEntity<?> openAll(@RequestParam("registId") Integer registId) {
        applyService.update(new LambdaUpdateWrapper<Checkapply>()
                .eq(Checkapply::getRegistid, registId)
                .eq(Checkapply::getState,    1)
                .set(Checkapply::getState,    2)
        );
        return ResponseEntity.ok().build();
    }

    @PostMapping("/checkapply/void")
    public ResponseEntity<?> voidBatch(@RequestBody List<Integer> ids) {
        applyService.update(new LambdaUpdateWrapper<Checkapply>()
                .in(Checkapply::getId,   ids)
                .set(Checkapply::getState, 3)
        );
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/checkapply/{id}")
    public ResponseEntity<?> deleteOne(@PathVariable Integer id) {
        var ca = applyService.getById(id);
        if (ca == null) return ResponseEntity.notFound().build();
        if (!Objects.equals(ca.getState(), 1)) {
            return ResponseEntity.badRequest().body("只有草稿状态才能删除");
        }
        applyService.removeById(id);
        return ResponseEntity.ok().build();
    }


    // ------------ 医技检验执行接口 ------------

    @GetMapping("/lab/applications")
    public ResponseEntity<List<Map<String,Object>>> listLabApplications(
            @RequestHeader("X-User-Id") Integer userId,
            @RequestParam(required=false) String caseNumber,
            @RequestParam(required=false) String kw
    ) {
        Integer deptId = userService.getById(userId).getDeptID();
        var apps = applyService.list(new LambdaQueryWrapper<Checkapply>()
                .eq(Checkapply::getRecordtype, 2)
                .eq(Checkapply::getState,      1)
        );
        var out = new ArrayList<Map<String,Object>>();
        for (var ca : apps) {
            var r = registerService.getById(ca.getRegistid());
            if (!Objects.equals(r.getDeptid(), deptId)) continue;
            if (caseNumber != null && !r.getCasenumber().equals(caseNumber)) continue;
            if (kw != null && !r.getRealname().contains(kw)) continue;
            out.add(Map.of("apply", ca, "register", r));
        }
        return ResponseEntity.ok(out);
    }
    @GetMapping("/checkapply/departments")
    public ResponseEntity<List<Map<String,Object>>> listCheckapplyDepartments() {
        // 1. 先拿所有 Fmeditem 里 distinct 的 deptid
        List<Integer> deptIds = itemService.list()
                .stream()
                .map(Fmeditem::getDeptid)
                .distinct()
                .toList();

        // 2. 查询这些 deptid 对应的 Department
        List<Map<String,Object>> out = deptService.listByIds(deptIds)
                .stream()
                .map(d -> Map.<String, Object>of(
                        "id",   d.getId(),
                        "name", d.getDeptname()
                ))
                .toList();

        return ResponseEntity.ok(out);
    }
    // ------------ 门诊“确诊”接口 ------------
    /**
     * GET /api/doctor/confirm/patient?registId=xxx
     * 拉取确诊页面需要的数据：患者注册信息 + 初步诊断 + 已完成结果录入的检验/检查项目列表
     */
    @GetMapping("/confirm/patient")
    public ResponseEntity<Map<String,Object>> getConfirmData(
            @RequestHeader("X-User-Id") Integer userId,
            @RequestParam("registId")   Integer registId) {

        // a) 患者注册信息（从 register 表取出 Gender 字段，是 constantitem 的主键）:contentReference[oaicite:0]{index=0}
        var reg = registerService.getById(registId);

        // 把 Gender ID 转成常量表里的名称
        Constantitem genderItem = constantitemService.getById(reg.getGender());
        String genderName = genderItem != null
                ? genderItem.getConstantname()
                : "";

        // 构建前端需要的 registerMap
        Map<String, Object> registerMap = new HashMap<>();
        registerMap.put("id",         reg.getId());
        registerMap.put("casenumber", reg.getCasenumber());
        registerMap.put("realname",   reg.getRealname());
        registerMap.put("sex",        genderName);       // ✅ 性别名称
        registerMap.put("age",        reg.getAge());
        // 如果不需要科室，这里可以省略 deptname
        // registerMap.put("deptname", deptService.getById(reg.getDeptID()).getDeptName());

        // b) 初步诊断（medicalrecord 表）
        var rec = recordService.getOne(
                new LambdaQueryWrapper<Medicalrecord>()
                        .eq(Medicalrecord::getRegistid, registId)
                        .last("LIMIT 1")
        );
        if (rec == null) {
            rec = new Medicalrecord();
            rec.setDiagnosis("");
        }

        // c) 已“完成结果录入”（state=6）的所有检验/检查项目
        List<Checkapply> done = applyService.list(new LambdaQueryWrapper<Checkapply>()
                .eq(Checkapply::getRegistid,   registId)
                .eq(Checkapply::getRecordtype, 2)
                .eq(Checkapply::getState,      6)
        );

        List<Map<String,Object>> tests = new ArrayList<>();
        for (Checkapply ca : done) {
            Fmeditem fi = itemService.getById(ca.getItemid());

            // 1) 项目名、结果、时间
            String itemName  = fi.getItemname();
            String result    = ca.getResult();
            Date   resultTime= ca.getResulttime();

            // 2) 检验人员（operator）
            String operatorName = "";
            if (ca.getResultoperid() != null) {
                User oper = userService.getById(ca.getResultoperid());
                operatorName = oper != null ? oper.getRealName() : "";
            }

            // 3) 所属科室（deptName）
            String deptName = "";
            if (fi.getDeptid() != null) {
                Department d = deptService.getById(fi.getDeptid());
                deptName = d != null ? d.getDeptname() : "";
            }

            Map<String,Object> m = new HashMap<>();
            m.put("name",        itemName);
            m.put("result",      result);
            m.put("resulttime",  resultTime);
            m.put("operator",    operatorName);  // 新增
            m.put("deptName",    deptName);      // 新增
            tests.add(m);
        }

        // 最终返回
        Map<String,Object> out = new HashMap<>();
        out.put("register", registerMap);
        out.put("record",   rec);
        out.put("tests",    tests);
        return ResponseEntity.ok(out);
    }


    /**
     * POST /api/doctor/confirm
     * { registId: xxx, diagnosis: "xxx" }
     * 保存“最终诊断”并将 register.visitstate 置为 4（已诊毕）
     */
    @PostMapping("/confirm")
    public ResponseEntity<?> saveConfirm(
            @RequestHeader("X-User-Id") Integer userId,
            @RequestBody Map<String,Object> body) {

        Integer registId = (Integer) body.get("registId");
        String  diag     = (String)  body.get("diagnosis");

        // 更新 medicalrecord.diagnosis
        recordService.update(null, new LambdaUpdateWrapper<Medicalrecord>()
                .eq(Medicalrecord::getRegistid, registId)
                .set(Medicalrecord::getDiagnosis, diag)
        );

        // 更新 register.visitstate = 4（已诊毕）
        registerService.update(null, new LambdaUpdateWrapper<Register>()
                .eq(Register::getId,          registId)
                .set(Register::getVisitstate, 4)
        );

        return ResponseEntity.ok().build();
    }

    // ------------ 医生信息接口 ------------

    @GetMapping("/info")
    public ResponseEntity<Map<String,Object>> getDoctorInfo(
            @RequestHeader(value="X-User-Id", required=false) Integer headerUserId,
            @RequestParam(value="userid",    required=false) Integer paramUserId
    ) {
        Integer userId = headerUserId!=null?headerUserId:paramUserId;
        User u = userService.getById(userId);
        return ResponseEntity.ok(Map.of("deptId", u.getDeptID()));
    }
}
